/**
 * 营销中心
 * mc-service
 * @authors 杨兴洲（of2502）
 * @date    2017/6/6 0006 11:09
 * @version 1.0
 * @last-modify  杨兴洲（of2502）
 */

import * as rp from 'request-promise-native';
import WxUserService from './weixin-user-service';
import UserService from './user-service';
import CONFIG from '../config';
import logger from '../util/logger';
import { encodeCipher } from '../util/aes-util';

const MC_HOST = CONFIG.MC_SERVER;
export default class MCService {
  /**
     * 批量关注
     * @returns {Promise<any>}
     */
  static async batchFollow({
    appID,
    openIds,
    salesCode
  }: {
    appID: string;
    openIds: string[];
    salesCode?: string;
  }): Promise<any> {
    // 获取粉丝数据
    let { userID } = await UserService.getInfoByAppID(appID);
    let access_token = await UserService.getAccessToken(userID);
    let result = await WxUserService.batchGetUserInfo({
      access_token,
      openid_list: openIds
    });
    //微信接口数据存在非法字符，导致返回数据是string类型
    if (result && typeof result == 'string') {
      result = eval('(' + result + ')');
    }
    let { user_info_list: userInfoList } = result;
    salesCode && logger.debug(userID, salesCode, userInfoList[0]);
    return rp({
      method: 'POST',
      uri: `${MC_HOST}/wxfans/follow`,
      body: {
        adminId: userID,
        domainType: '0032',
        fansInfos: userInfoList.map(userInfo => {
          const { openid, subscribe, nickname, sex, city, province, headimgurl, unionid } = userInfo;
          return {
            openId: openid,
            nick: nickname,
            sex: sex === 1 ? 'M' : sex === 0 ? 'NA' : 'F',
            province,
            city,
            avatar: headimgurl,
            salesCode
          };
        })
      },
      json: true
    })
      .then((data: any) => data)
      .catch(error => console.log(error));
  }

  /**
     * 批量取消关注
     * @openIds
     * @appID
     * @returns {Promise<any>}
     */
  static async batchUnfollow({ appID, openIds }: { appID: string; openIds: string[] }): Promise<any> {
    // console.log(openId);
    let { userID } = await UserService.getInfoByAppID(appID);
    return rp({
      method: 'POST',
      uri: `${MC_HOST}/wxfans/unfollow`,
      body: {
        adminId: userID,
        domainType: '0032',
        openIds
      },
      json: true
    })
      .then((data: any) => data)
      .catch(error => console.log(error));
  }

  /**
     * 某一公众号所有粉丝关注
     */
  static async batchAllFollow(userID): Promise<any> {
    const access_token = await UserService.getAccessToken(userID);
    const { authorizer_appid: appID } = await UserService.getInfo(userID);
    const getOpenIdList = async ({ next_openid }: { next_openid?: string }) => {
      let { data: { openid: openIds } } = await WxUserService.getList({ access_token, next_openid });
      let list = openIds || [];
      for (let i = 1; i <= Math.ceil(list.length / 100); i++) {
        let ids = list.slice((i - 1) * 100, i * 100);
        await MCService.batchFollow({ appID, openIds: ids }).then(data => {
          console.log(data, list.length, ids.length);
        });
      }
      if (list.length < 10000) {
        console.log('openid数据加载完毕');
        return;
      }
      await getOpenIdList({ next_openid: list[9999] });
    };
    await getOpenIdList({});
  }

  /**
     * 某一公众号所有粉丝取消关注
     */
  static async batchAllUnfollow(userID): Promise<any> {
    const access_token = await UserService.getAccessToken(userID);
    const { authorizer_appid: appID } = await UserService.getInfo(userID);
    const getOpenIdList = async ({ pageSize = 100, next_openid }: { pageSize?: number; next_openid?: string }) => {
      let { data: { openid: openIds } } = await WxUserService.getList({ access_token, next_openid });
      let list = openIds || [];
      let count = Math.min(+pageSize, list.length);
      await MCService.batchUnfollow({ appID, openIds });
      if (count < pageSize) {
        console.log('openid数据加载完毕');
        return;
      }
      await getOpenIdList({ next_openid: openIds[count - 1] });
    };
    await getOpenIdList({});
  }
  /**
     * 通知营销中心取消授权绑定
     * @openIds
     * @appID
     * @returns {Promise<any>}
     */
  static async unbind(userID): Promise<any> {
    let authInfo = _generatorKey(userID);
    logger.info(`通知营销中心，当前用户${userID}解绑`, authInfo);
    return rp({
      method: 'POST',
      uri: `${MC_HOST}/wxfans/unbind`,
      headers: {
        Authorization: encodeCipher(authInfo)
      },
      body: {
        adminId: userID,
        domainType: '0032'
      },
      json: true
    })
      .then((data: any) => data)
      .catch(error => console.log(error));
  }
}
/**
 * 根据userID 生成加密信息
 * @param userID
 * @returns {string}  eg:'yyyyMMddHHmmss00123456'
 * @private
 */
function _generatorKey(userID: string): string {
  let now = new Date();
  let result = '';
  result += now.getFullYear();
  result += _completeVal(now.getMonth() + 1, 2);
  result += _completeVal(now.getDate(), 2);
  result += _completeVal(now.getHours(), 2);
  result += _completeVal(now.getMinutes(), 2);
  result += _completeVal(now.getSeconds(), 2);
  result += _completeVal(userID.replace(/[^\d]/g, ''), 8);
  return result;
}
/**
 * 补齐数值位数
 * @param value
 * @param len
 * @returns {string}
 * @private
 */
function _completeVal(value: any, len: number): string {
  value += '';
  if (value.length < len) {
    let str = Math.pow(10, len - value.length) + '';
    str = str.substring(1);
    value = str + value;
  }
  return value;
}
